<template>
  <div class="tabs-container">
    <!-- 左滚动按钮 -->
    <button 
      class="scroll-btn left" 
      @click="scrollLeft" 
      :disabled="!canScrollLeft"
      v-show="showScrollButtons"
    >
      <el-icon><ArrowLeft /></el-icon>
    </button>
    
    <!-- 页签滚动区域 -->
    <div 
      class="tabs-wrapper" 
      ref="tabsWrapper"
      @wheel.prevent="handleWheel"
    >
      <div 
        class="tabs-scroll" 
        ref="tabsScroll" 
        :style="{ transform: `translateX(${scrollOffset}px)` }"
        @mousedown="startDrag"
      >
        <div 
          v-for="tab in tabs" 
          :key="tab.path"
          class="tab-item"
          :class="{ 
            active: isActive(tab), 
            fixed: tab.fixed,
            'has-close': !tab.fixed
          }"
          @click="switchTab(tab)"
          @contextmenu.prevent="showContextMenu($event, tab)"
        >
          <span class="tab-title">{{ tab.title }}</span>
          <el-icon 
            v-if="!tab.fixed" 
            class="tab-close" 
            @click.stop="closeTab(tab)"
          >
            <Close />
          </el-icon>
        </div>
      </div>
    </div>
    
    <!-- 右滚动按钮 -->
    <button 
      class="scroll-btn right" 
      @click="scrollRight" 
      :disabled="!canScrollRight"
      v-show="showScrollButtons"
    >
      <el-icon><ArrowRight /></el-icon>
    </button>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { ArrowLeft, ArrowRight, Close } from '@element-plus/icons-vue';

interface TabItem {
  path: string;
  title: string;
  fixed?: boolean;
  fullPath: string;
}
const route = useRoute();
const router = useRouter();
// 标签页列表
const tabs= ref([] as TabItem[]);
// 缓存的视图名称
const cachedViews = ref<string[]>([]);
const activeTab= ref('');
const emit = defineEmits(['tab-click', 'tab-close', 'tab-contextmenu']);

// DOM 引用
const tabsWrapper = ref<HTMLElement | null>(null);
const tabsScroll = ref<HTMLElement | null>(null);

// 滚动状态
const scrollOffset = ref(0);
const isDragging = ref(true);
const startX = ref(0);
const startScrollOffset = ref(0);
const showScrollButtons = ref(false);

// 计算属性
const canScrollLeft = computed(() => scrollOffset.value < 0);
const canScrollRight = computed(() => {
  if (!tabsWrapper.value || !tabsScroll.value) return false;
  console.log('tabsScroll', tabsScroll.value.scrollWidth  , scrollOffset.value,tabsWrapper.value.offsetWidth);
  return tabsScroll.value.scrollWidth + scrollOffset.value > tabsWrapper.value.offsetWidth;
});

// 页签操作
const isActive = (tab: TabItem) => tab.path === activeTab.value;
// 初始化标签页
const initTabs = () => {
  
  for (let i = 0; i < 15; i++) {
    tabs.value.push({
      title: i + "未命名",
      path: "test" + i,
      fullPath: "test" + i,
    });
  }
  if (tabs.value.some((tab) => tab.path === route.path)) return;
  // ✅ 1. 确保首页标签始终存在
  const homeTab = {
    title: "首页",
    path: "/home",
    fullPath: "/home",
  };

  if (!tabs.value.some((tab) => tab.path === "/home")) {
    tabs.value.unshift(homeTab); // 放在第一个位置
  }

  // ✅ 2. 如果是根路径 /，则跳转到首页
  if (route.path === "/") {
    router.replace("/home"); // 使用 replace 避免历史记录污染
    return;
  }

  // ✅ 3. 其他路由正常处理
  if (tabs.value.some((tab) => tab.path === route.path)) return;

  if (!route.meta.title) {
    router.push("/404"); // 默认回退到首页
    return;
  }
  tabs.value.push({
    title: (route.meta.title as string) || "未命名",
    path: route.path,
    fullPath: route.fullPath,
  });

  if (route.meta.keepAlive) {
    cachedViews.value.push(route.name as string);
  }
};
const switchTab = (tab: TabItem) => {
  emit('tab-click', tab);
  nextTick(scrollToActiveTab);
};

const closeTab = (tab: TabItem) => {
  emit('tab-close', tab);
};

const showContextMenu = (e: MouseEvent, tab: TabItem) => {
  emit('tab-contextmenu', { event: e, tab });
};

// 滚动方法
const scrollLeft = () => {
  console.log('scrollLeft');
  if (!tabsWrapper.value) return;
  console.log('scrollLeft');
  const newOffset = Math.min(0, scrollOffset.value + tabsWrapper.value.offsetWidth * 0.8);
  console.log('scrollLeft', newOffset);
  scrollOffset.value = newOffset;
};

const scrollRight = () => {
console.log('尝试向右滚动');
  
  if (!tabsWrapper.value || !tabsScroll.value) {
    console.error('DOM元素未准备好');
    return;
  }

  // 调试输出当前宽度信息
  console.log('容器宽度:', tabsWrapper.value.offsetWidth);
  console.log('内容宽度:', tabsScroll.value.scrollWidth);
  console.log('当前偏移:', scrollOffset.value);

  // 计算最大可滚动距离（负数）
  const maxOffset = tabsWrapper.value.offsetWidth - tabsScroll.value.scrollWidth;
  console.log('最大偏移:', maxOffset);

  // 计算新偏移量（每次滚动容器宽度的80%）
  const scrollAmount = tabsWrapper.value.offsetWidth * 0.8;
  const newOffset = scrollOffset.value - scrollAmount;
  
  // 确保不会滚动超过最大偏移量
  const clampedOffset = Math.max(maxOffset, newOffset);
  console.log('计算后的新偏移:', clampedOffset);

  scrollOffset.value = clampedOffset;
};

// 自动滚动到当前激活页签
const scrollToActiveTab = () => {
  nextTick(() => {
    if (!tabsWrapper.value || !tabsScroll.value) return;
    
    const activeTab = document.querySelector('.tab-item.active');
    if (!activeTab) return;
    
    const tabRect = activeTab.getBoundingClientRect();
    const wrapperRect = tabsWrapper.value.getBoundingClientRect();
    
    // 如果标签在左侧外
    if (tabRect.left < wrapperRect.left) {
      scrollOffset.value += wrapperRect.left - tabRect.left + 10;
    } 
    // 如果标签在右侧外
    else if (tabRect.right > wrapperRect.right) {
      scrollOffset.value -= tabRect.right - wrapperRect.right + 10;
    }
    
    // 确保不超出边界
    const maxOffset = 0;
    const minOffset = tabsWrapper.value.offsetWidth - tabsScroll.value.offsetWidth;
    scrollOffset.value = Math.max(minOffset, Math.min(maxOffset, scrollOffset.value));
  });
};

// 拖拽功能
const startDrag = (e: MouseEvent) => {
  if (!tabsScroll.value) return;
  
  isDragging.value = true;
  startX.value = e.clientX;
  startScrollOffset.value = scrollOffset.value;
  
  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('mouseup', stopDrag);
  tabsScroll.value.style.cursor = 'grabbing';
  tabsScroll.value.style.transition = 'none';
};

const handleDrag = (e: MouseEvent) => {
  if (!isDragging.value || !tabsWrapper.value || !tabsScroll.value) return;
  
  const deltaX = e.clientX - startX.value;
  let newOffset = startScrollOffset.value + deltaX;
  
  // 限制滚动范围
  const maxOffset = 0;
  const minOffset = tabsWrapper.value.offsetWidth - tabsScroll.value.offsetWidth;
  newOffset = Math.max(minOffset, Math.min(maxOffset, newOffset));
  
  scrollOffset.value = newOffset;
};

const stopDrag = () => {
  isDragging.value = false;
  if (tabsScroll.value) {
    tabsScroll.value.style.cursor = '';
    tabsScroll.value.style.transition = 'transform 0.3s ease';
  }
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDrag);
};

// 鼠标滚轮滚动
const handleWheel = (e: WheelEvent) => {
  if (!tabsWrapper.value) return;
  
  // 水平滚动
  if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
    e.preventDefault();
    scrollOffset.value = Math.max(
      tabsWrapper.value.offsetWidth - (tabsScroll.value?.offsetWidth || 0),
      Math.min(0, scrollOffset.value + e.deltaX)
    );
  }
};

// 检查是否需要显示滚动按钮
const checkScrollButtons = () => {
  if (!tabsWrapper.value || !tabsScroll.value) {
    showScrollButtons.value = false;
    return;
  }
  
  showScrollButtons.value = tabsScroll.value.offsetWidth > tabsWrapper.value.offsetWidth;
  showScrollButtons.value = true;
};

// 生命周期
onMounted(async() => { 
  await nextTick();
  window.addEventListener('resize', checkScrollButtons);
  checkScrollButtons();
  scrollToActiveTab();
});

onUnmounted(() => {
  window.removeEventListener('resize', checkScrollButtons);
  stopDrag();
});
// 监听路由变化
watch(
  () => route.path,
  () => {
    initTabs();
    // calculateScrollPosition();
  },
  { immediate: true }
);
// 监听tabs变化
watch(
  () => tabs.value.length,
  () => {
    // calculateScrollPosition();
  }
);
// 监听变化
watch(() => activeTab.value, scrollToActiveTab);
watch(() => tabs.value.length, () => {
  nextTick(() => {
    checkScrollButtons();
    scrollToActiveTab();
  });
});
</script>

<style scoped lang="scss">
.tabs-container {
  display: flex;
  align-items: center;
  height: 40px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  position: relative;
  user-select: none;
}

.tabs-wrapper {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.tabs-scroll {
  height: 100%;display: flex;
  transition: transform 0.3s ease;
  white-space: nowrap;
  cursor: grab;
  
  &:active {
    cursor: grabbing;
  }
}

.tab-item {
  position: relative;
  display: inline-flex;
  align-items: center;
  height: 100%;
  padding: 0 16px;
  cursor: pointer;
  border: 1px solid transparent;
  border-bottom: none;
  transition: all 0.3s;
  font-size: 14px;
  
  &:hover {
    background: #f5f5f5;
    
    .tab-close {
      opacity: 1;
    }
  }
  
  &.active {
    background: #fff;
    border-color: #e8e8e8;
    border-bottom-color: #fff;
    color: var(--el-color-primary);
    
    .tab-close {
      opacity: 1;
      color: var(--el-text-color-secondary);
      
      &:hover {
        color: var(--el-text-color-primary);
      }
    }
  }
  
  &.has-close {
    padding-right: 8px;
  }
}

.tab-title {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tab-close {
  margin-left: 4px;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.2s;
  color: var(--el-text-color-placeholder);
  
  &:hover {
    color: var(--el-text-color-primary);
  }
}

.scroll-btn {
  width: 28px;
  height: 100%;
  background: #fff;
  border: none;
  outline: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  z-index: 1;
  
  &:disabled {
    opacity: 0.3;
    cursor: not-allowed;
  }
  
  &:not(:disabled):hover {
    background: #f5f5f5;
    color: var(--el-text-color-primary);
  }
  
  &.left {
    box-shadow: 4px 0 8px rgba(0, 0, 0, 0.05);
  }
  
  &.right {
    box-shadow: -4px 0 8px rgba(0, 0, 0, 0.05);
  }
}

@media (max-width: 768px) {
  .scroll-btn {
    display: none;
  }
  
  .tabs-wrapper {
    margin: 0 8px;
  }
}
</style>